const { createCanvas, loadImage } = require('canvas');
const fs = require("fs");
const readline = require('readline');
const filename = "0001raw";
let cag = [
    "tags",
    "input",
    "buttons",
    "imagesUpload",
    "links",
    "select",
    "radio",
    "textarea",
    "datePicker",
    "rate",
    "rangePicker",
    "switch",
    "timePicker",
    "checkbox",
];
(
    async () => {
        let image = await loadImage('./' + filename + '.jpg')
        const canvas = createCanvas(image.naturalWidth, image.naturalHeight)
        const ctx = canvas.getContext('2d')
        console.log(image.naturalWidth, image.naturalHeight)
        ctx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight)
        ctx.beginPath();
        ctx.lineWidth = "1";
        ctx.strokeStyle = "blue";
        // let res = fs.createReadStream(path.join(__dirname, targetFolder, filelist[i]))
        let res = fs.createReadStream('./' + filename + '.txt')
        // console.log(res)
        const rl = readline.createInterface({
            input: res, //or fileStream 
            output: res
        });
        ctx.font = "20px Arial";
        // let res = await fs.readFileSync('./train/labels_with_ids/S1001.txt', "utf8")
        for await (const line of rl) {
            let temp_arr = line.split(/[\s\n]/)
            let x_center = +temp_arr[1] * image.naturalWidth
            let y_center = +temp_arr[2] * image.naturalHeight
            let x_width = +temp_arr[3] * image.naturalWidth
            let y_width = +temp_arr[4] * image.naturalHeight
            ctx.strokeText(cag[+temp_arr[0]], Math.round(x_center - x_width / 2), Math.round(y_center - y_width / 2), 500)
            console.log(cag[+temp_arr[0]], Math.round(x_center - x_width / 2), Math.round(y_center - y_width / 2), x_width, y_width)
            ctx.rect(Math.round(x_center - x_width / 2), Math.round(y_center - y_width / 2), x_width, y_width);
            ctx.stroke();
        }
        fs.writeFileSync(filename + "yolo.jpg", canvas.toBuffer(), "binary");
    }
)()
